package su.msk.jet.team01.chatik.client.ui.swing;

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.LinkedList;
import java.util.Queue;

@SuppressWarnings("serial")
public class TextBox extends JTextField {

	private static final int DEFAULT_COLUMS_NUMBER = 50;
	private final Queue<String> msgQueue = new LinkedList<String>();

	TextBox() {
		super(DEFAULT_COLUMS_NUMBER);

		addKeyListener(new KeyListener() {

			@Override
			public void keyPressed(final KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					releaseMessage();
				}
			}

			@Override
			public void keyReleased(final KeyEvent e) {
			}

			@Override
			public void keyTyped(final KeyEvent e) {
			}
		});
	}

	synchronized String readMessage() {
		String result = msgQueue.poll();
		while (result == null) {
			try {
				wait();
			} catch (InterruptedException e) {
			}
			result = msgQueue.poll();
		}
		return result;
	}

	synchronized void releaseMessage() {
		String text = getText();
		if (!text.equals("") && !text.equals("\n")) {
			msgQueue.add(getText());
			setText("");
			notify();
		}
	}
}
